package com.partner.share.work.mq.controller;


import com.partner.share.work.mq.construction.ActiveMQTopicConst;
import com.partner.share.work.mq.consumer.Consumer;
import com.partner.share.work.mq.producer.Producer;
import com.partner.share.work.websocket.server.WebsocketService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.jms.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * @author pengyangyan
 * @version 1.0.0
 * @date 2019年09月29日 14:01:00
 */
@Slf4j
@Controller
public class ChatController {

    @Autowired
    WebsocketService websocketService;

    private Producer producer = null;

    @GetMapping("/")
    public String login() throws JMSException {
        return "login";
    }

    @GetMapping("/index/{username}")
    public String index(@PathVariable("username") String username, Model model,HttpServletRequest request){
        HttpSession session = request.getSession();
        model.addAttribute("user",username);
        try {
            Consumer consumer = new Consumer(websocketService);
            consumer.receiveMessage();
            session.setAttribute(username,consumer);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "index";
    }

    @GetMapping("/login")
    @ResponseBody
    public String loginUser(@RequestParam("username") String username){
        return username;
    }

    @GetMapping("/send")
    @ResponseBody
    public void send(@RequestParam("content") String content,@RequestParam("user")String user) throws JMSException {
        //主题模式发布消息
//        activeMQTopicPublisher.publishMsg(ActiveMQTopicConst.TOPIC_NAME_WEBSOCKET_SYSTEM_NOTICE,content,user);
        try {
            producer = new Producer();
            producer.sendMessage(ActiveMQTopicConst.TOPIC_NAME_WEBSOCKET_SYSTEM_NOTICE,content,user);
        } catch (JMSException e) {
            e.printStackTrace();
            log.error("消息发布失败!");

        }finally {
            producer.close();
        }
    }

    @GetMapping("/close")
    @ResponseBody
    public void closeConsumer(@RequestParam("username") String username,HttpServletRequest request){
        HttpSession session = request.getSession();
        Consumer consumer = (Consumer) session.getAttribute(username);
        try {
            consumer.close();
        } catch (JMSException e) {
            e.printStackTrace();
            log.error("消费者关闭失败!");
        }
    }


}
